package cc.tantivy.p2p;

import cc.tantivy.persistence.InfoHashDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by Jason on 2017/2/9.
 */
@Service
public class DHTInfoHashService {
    private static final Logger logger = LoggerFactory.getLogger(DHTInfoHashService.class);

    private final ExecutorService dao = Executors.newSingleThreadExecutor();
    private final BlockingQueue<String> hashQueue = new LinkedBlockingQueue<>();

    @Autowired
    InfoHashDao infoHashDao;

    public DHTInfoHashService() {
        dao.execute(() -> {
            for (; ; ) {
                try {
                    String infoHash = hashQueue.take();
                    Integer isExist = infoHashDao.isExistInfoHash(infoHash);
                    if (isExist == null) {
                        infoHashDao.insertInfoHash(infoHash);
                    } else {
                        infoHashDao.updateHeat(infoHash);
                    }
                } catch (Exception e) {
                    logger.error(e.getLocalizedMessage());
                }
            }
        });
    }

    public void saveHash(String infoHash) {
        StringBuilder msg = new StringBuilder();
        for (char c : infoHash.toCharArray()) {
            String hs = Integer.toHexString(c);
            if (hs.length() == 1) {
                msg.append(0);
            }
            msg.append(hs);
        }
        try {
            hashQueue.put(msg.toString());
        } catch (InterruptedException e) {
            logger.error(e.getLocalizedMessage());
        }
    }

}
